<?php

class SiteController extends FrontController
{

    public $agree = false;

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('oauth'),
                'users'   => array('*'),
            ),
        );
    }

    public function actionTestEmail()
    {
        try
        {

            MyEmail::send_error('test_send email ' . Utils::genRandomString(4));
            echo 'xxx';
        }
        catch (Exception $ex)
        {
            echo $ex;
        }
    }

    public function actions()
    {
        return array(
            'oauth'      => array(
                // the list of additional properties of this action is below
                'class'      => 'ext.hoauth.HOAuthAction',
                // Yii alias for your user's model, or simply class name, when it already on yii's import path
                // default value of this property is: User
                'model'      => 'Users',
                // map model attributes to attributes of user's social profile
                // model attribute => profile attribute
                // the list of avaible attributes is below
                'attributes' => array(
                    'email'      => 'email',
                    'firstname'  => 'firstName',
                    'lastname'   => 'lastName',
                    'gender'     => 'gender',
                    'address'    => 'address',
                    'photo'      => 'photoURL',
                    'home_phone' => 'phone',
                    'website'    => 'webSiteURL',
//                    'photo' => 'country',
//                    'birthday' => 'birthDate',
//                    // you can also specify additional values, 
//                    // that will be applied to your model (eg. account activation status)
//                    'acc_status' => 1,
                ),
            ),
            // this is an admin action that will help you to configure HybridAuth 
            // (you must delete this action, when you'll be ready with configuration, or 
            // specify rules for admin role. User shouldn't have access to this action!)
            'oauthadmin' => array(
                'class' => 'ext.hoauth.HOAuthAdminAction',
            ),
            'captcha'    => array(
                'class'     => 'CCaptchaAction',
                'backColor' => 0xFFFFFF
            ),
        );
    }

    public $layout = '//layouts/home';

    public function actionIndex()
    {

        $cri            = new CDbCriteria();
        $cri->condition = 'isshow=:i';
        $cri->params    = array(
            ':i' => Category::SHOW_HOMEPAGE
        );
        $cri->limit     = 10;

        $categories = Category::model()->findAll($cri);


        $cri2            = new CDbCriteria();
        $cri2->condition = 'status=' . Slider::STATUS_ACTIVE;
        $cri2->order     = 'rank DESC';

        $slider = Slider::model()->findAll($cri2);
        $this->render('index', array(
            'categories' => $categories,
            'slider'     => $slider
        ));
//        $l = new CLogger();
//        $l->log('test', CLogger::LEVEL_ERROR, 'test');
//        
//
//        $t = new CWebLogRoute();
//        $t->showInFireBug = TRUE;
//        $t->processLogs($l->getLogs());
    }

    public function actionLogin()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $model = new UserLoginForm;
            // collect user input data

            $model->email    = trim($_POST['email']);
            $model->password = trim($_POST['password']);

            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
            {
                $log       = new AccessLog();
                $log->ip   = ip2long(Yii::app()->request->userHostAddress);
                $user      = Users::model()->findByPk(Yii::app()->user->id);
                $log->name = $user->email;
                $log->role = $user->type;
                $log->time = time();
                $log->save();

                echo json_encode(array(
                    'status' => 'ok'
                ));
                Yii::app()->end();
            }
            else
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
        }
    }

    public function actionSignup()
    {
        $model = new UserSignUp('signup-frontend');

        $model->firstname    = $_POST['firstname'];
        $model->lastname     = $_POST['lastname'];
        $model->email        = $_POST['email'];
        $model->mobile_phone = $_POST['mobile_phone'];
        $model->new_pass     = $_POST['new_pass'];
        $model->repassword   = $_POST['repassword'];
        $bday                = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
        $model->birthday     = strtotime($bday);
        $model->type         = Users::TYPE_CUSTOMER;
        $model->status       = Users::STATUS_ACTIVE;
        $model->date_created = time();
        $model->subscribe    = $_POST['subscribe'];

        if ($model->validate() AND $model->save())
        {
            if ($model->subscribe == 1)
            {
                $subcribe        = new Subscription;
                $subcribe->email = $model->email;
                $subcribe->save();
            }
            MyEmail::sendToNewUser($model, $model->new_pass);
            $model->completeCreateUser();
            echo json_encode(array(
                'status' => 'ok'
            ));
        }
        else
        {
            echo CActiveForm::validate($model);
        }
        Yii::app()->end();
    }

    public function actionForgotPass()
    {
        $model = new Users();

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'forgotpwd-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        if (isset($_POST['Users']))
        {
            $model->attributes = $_POST['Users'];

            if ($model->validate())
            {
                $user = Users::model()->find('LOWER(email)=:email AND type=:type', array(
                    ':email' => strtolower($model->email),
                    ':type'  => Users::TYPE_CUSTOMER
                ));
                if ($user == NULL)
                {
                    echo CJSON::encode(array('Users_email' => array('Incorrect email')));
                    Yii::app()->end();
                }
                echo 1;
                EmailConfirm::sendPasswordReset($user->email, $user->ukey, $user->name);
            }
            else
            {
                echo CActiveForm::validate($model);
            }
            Yii::app()->end();
        }
    }

    public function actionPasswordConfirm()
    {
        $this->layout = '//layouts/main';

        if (empty($_GET))
        {
            Yii::app()->user->setFlash('error', 'Something wrong or time expired!');
        }

        $criteria         = new CDbCriteria();
        $criteria->select = array('ukey', 'id', 'email', 'firstname', 'lastname', 'password', 'salt');
        $criteria->compare('ukey', $_GET['ukey']);

        $customer = Users::model()->find($criteria);

        $confirm = EmailConfirm::model()->find('email=:e AND code=:c AND expire > :t AND type=:type', array(
            ':e'    => $customer->email,
            ':c'    => $_GET['code'],
            ':t'    => time(),
            ':type' => EmailConfirm::TYPE_PASSWORD_RESET
        ));

        if (!$customer or ! $confirm)
        {
            Yii::app()->user->setFlash('error', 'Something wrong or time expired!');
            $this->render('_confirm');
        }
        else
        {
            $new_pass = Utils::genRandomString();

            $customer->new_pass = $new_pass;

            if ($customer->save())
            {
                $mail         = new MyEmail();
                $mail->type   = MyEmail::TYPE_PASS_RECOVER;
                $mail->to     = $customer->email;
                $mail->params = array(
                    MyEmail::CODE_USER_NAME => $customer->name,
                    MyEmail::CODE_PASSWORD  => $customer->new_pass,
                );

                $mail->send();

                Yii::app()->user->setFlash('success', "New password has been sent to your email.");

                $confirm->delete();

                $this->render('_confirm');
            }
        }
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->request->urlReferrer);
    }

    public function actionError()
    {
//        $error = Yii::app()->errorHandler->error;
//        if ($error)
//        {
        $this->render('error');
//        }
    }

    public function actionLoginfb()
    {
//        session_start();
        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection

        $app_id       = "1419559608266256"; //change this
        $redirect_url = "http://voithan.com/demo/webmaster/frontend/site/Fbcallback"; //change this

        $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
                . $app_id . "&redirect_uri=" . urlencode($redirect_url) . "&state="
                . $_SESSION['state'] . "&scope=user_birthday,email";

        $this->redirect($dialog_url);
    }

    public function actionFbcallback()
    {
        $app_id       = "1419559608266256"; //change this
        $app_secret   = "a7d5ec135d7ba4743b692d306229b971"; //change this
        $redirect_url = "http://voithan.com/demo/webmaster/frontend/site/Fbcallback"; //change this


        $code = $_REQUEST["code"];
        session_start();

        if (empty($code))
        {
            header('Location: http://voithan.com/demo/webmaster/frontend/site/'); //change this
            exit(0);
        }

        $token_url = "https://graph.facebook.com/oauth/access_token?"
                . "client_id=" . $app_id . "&redirect_uri=" . urlencode($redirect_url)
                . "&client_secret=" . $app_secret . "&code=" . $code;

        $response = file_get_contents($token_url);
        $params   = null;
        parse_str($response, $params);

        if ($params == null)
        {
            echo "Unable to get Access Token";
            exit(0);
        }

        if ($_SESSION['state'] == null || ($_SESSION['state'] != $_REQUEST['state']))
        {
//		die("May be CSRF attack");
        }

        $_SESSION['access_token'] = $params['access_token']; //save token is session 

        $user = $this->getUserDetails($params['access_token']);
        $this->autoFBlogin($user->email);
    }

    private function getUserDetails($access_token)
    {
        $graph_url = "https://graph.facebook.com/me?access_token=" . $access_token;
        $user      = json_decode(file_get_contents($graph_url));
        if ($user != null && isset($user->name))
            return $user;

        return null;
    }

    public function actionContact()
    {

        $this->layout = '//layouts/browser';

        $contact = new Contact();
        $contact->setScenario("");
//           $contact=new Users();
        $this->performAjaxValidation($contact);
        if (isset($_POST['Contact']))
        {
            $contact->attributes = $_POST['Contact'];

            if ($contact->validate() && $contact->save(false))
            {
                try
                {
                    MyEmail::send_new_contact_to_admin($contact);
                    MyEmail::send_new_contact_to_user($contact);
                }
                catch (Exception $ex)
                {
                    MyEmail::send_error('can not send email contact Sitecontroller.php line:292');
                }

                Yii::app()->user->setFlash('contact_sucessfully', Yii::t('frontend', 'Thank you for contacting us. We will respond to you as soon as possible.'));

                Yii::app()->request->redirect(Yii::app()->createUrl('frontend/site/contact'));
            }
            else
            {
                MyEmail::send_error('can not save contact Sitecontroller.php line:230');
                Yii::app()->user->setFlash('contact_error', Yii::t('frontend', 'Can not send email'));
            }
        }
//        die('xxx');
        $this->render('contact', array(
            'contact' => $contact
        ));
    }

    public function actionPricing()
    {
        $this->layout = '//layouts/browser';

        $page_agreement = Page::model()->find('id = :i and status = :s', array(
            ':i' => 4, //test
            ':s' => Page::STATUS_PUBLIC,
        ));

        $this->render('pricing', array('agreement' => $page_agreement));
    }

    public function actionPurchaseSuccess()
    {
        $this->layout = '//layouts/main';
        $this->render('_purchase_success');
    }

    /**
     * Performs the AJAX validation.
     * @param Subscription $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] === 'contact-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
